var express = require('express')
var md5 = require('md5-node')

var User = require('./models/user')
var Topic = require('./models/topic')
var Comment = require('./models/comment')

var router = express.Router()

// 渲染首页
router.get('/', async (req, res) => {
  try {
    const data = await Topic.find({})
    res.render('index.html', {
      user: req.session.user,
      topics: data
    })
  } catch (e) {
    // throw e
    return console.log(e)
  }
})

// 渲染登录页面
router.get('/login', function (req, res) {
  res.render('login.html')
})
// 处理登录请求
router.post('/login', function (req, res, next) {
  // 1. 获取表单数据
  // 2. 查询数据库用户名密码是否正确
  // 3. 发送响应数据
  var body = req.body

  User.findOne({
    email: body.email,
    // password: body.password
    password: md5(md5(body.password))
  }, function (err, user) {
    if (err) {
      return next(err)
    }

    // 如果邮箱和密码匹配，则 user 是查询到的用户对象，否则就是 null
    if (!user) {
      return res.status(200).json({
        err_code: 1,
        message: 'Email or password is invalid.'
      })
    }

    // 用户存在，登陆成功，通过 Session 记录登陆状态
    req.session.user = user

    res.status(200).json({
      err_code: 0,
      message: 'OK'
    })
  })
})
// 渲染注册页面
router.get('/register', function (req, res, next) {
  res.render('register.html')
})
// 处理注册请求
router.post('/register', function (req, res, next) {
  // 1. 获取表单提交的数据
  //    req.body
  // 2. 操作数据库
  //    判断改用户是否存在
  //    如果已存在，不允许注册
  //    如果不存在，注册新建用户
  // 3. 发送响应
  var body = req.body
  User.findOne({
    $or: [
      { email: body.email },
      { nickname: body.nickname }
    ]
  }, function (err, data) {
    if (err) {
      // return res.status(500).json({
      //   success: false,
      //   message: '服务端错误'
      // })
      return next(err)
    }
    if (data) {
      // 邮箱或者昵称已存在
      return res.status(200).json({
        err_code: 1,
        message: 'Email or nickname aleady exists.'
      })
      return res.send(`邮箱或者密码已存在，请重试`)
    }

    // 对密码进行 md5 重复加密
    body.password = md5(md5(body.password))

    new User(body).save(function (err, user) {
      if (err) {
        return next(err)
      }

      // 注册成功，使用 Session 记录用户的登陆状态
      req.session.user = user

      // Express 提供了一个响应方法：json
      // 该方法接收一个对象作为参数，它会自动帮你把对象转为字符串再发送给浏览器
      res.status(200).json({
        err_code: 0,
        message: 'OK'
      })

      // 服务端重定向只针对同步请求才有效，异步请求无效
      // res.redirect('/')
    })
  })
})

// 退出登录
router.get('/logout', function (req, res) {
  // 清除登陆状态
  req.session.user = null

  // 重定向到登录页
  res.redirect('/login')
})

// 渲染话题详情页
router.get('/topics/show', async (req, res) => {
  const id = (req.query.id).replace(/\"/g, "")
  try {
    const topic = await Topic.findOne({ _id: id })
    const comments = await Comment.find({ articleId: id })
    res.render('topic/show.html', {
      comments: comments,
      topic: topic,
      user: req.session.user
    })
  } catch (e) {
    throw e
  }
})
// 处理发表的评论请求
router.post('/topics/show', async (req, res) => {
  const body = req.body
  const articleId = body.articleId.replace(/\"/g, "")
  try {
    const data = await Topic.findOne({ _id: articleId })
    const comment = {}
    comment.articleId = articleId
    comment.email = data.email
    comment.nickname = req.session.user.nickname
    comment.comments = body.comments
    await new Comment(comment).save()
    res.status(200).json({
      err_code: 0,
      message: 'OK'
    })
  } catch (e) {
    res.status(500).json({
      err_code: 500,
      message: e.message
    })
  }
})

// 渲染发布页面
router.get('/topics/new', (req, res) => {
  res.render('topic/new.html', {
    user: req.session.user
  })
})
// 处理发布博客请求
router.post('/topics/new', async (req, res) => {
  const body = req.body
  body["email"] = req.session.user.email
  body["nickname"] = req.session.user.nickname
  try {
    await new Topic(body).save()
    res.status(200).json({
      err_code: 0,
      message: 'OK'
    })
  } catch (e) {
    return res.status(500).json({
      err_code: 500,
      message: e.message
    })
  }
})


// 渲染用户个人页面
router.get('/settings/profile', (req, res) => {
  res.render('settings/profile.html', {
    user: req.session.user
  })
})
// 处理修改个人信息请求
router.post('/settings/profile', async (req, res) => {
  const body = req.body
  try {
    // 跟新用户修改的信息
    await User.updateOne(
      { email: req.session.user.email },
      {
        $set: { "nickname": body.nickname, "bio": body.bio, "gender": body.gender, "birthday": body.birthday },
        $currentDate: { "lastModified": true }
      });
    // 更改信息以后 重新查询数据库 更新 session 里面的 user
    const newUser = await User.findOne({ email: req.session.user.email, password: req.session.user.password })
    req.session.user = newUser

    res.status(200).json({
      err_code: 0,
      message: 'OK'
    })
  } catch (e) {
    return res.status(500).json({
      err_code: 500,
      message: e.message
    })
  }
})


// 渲染用户账号设置
router.get('/settings/admin', (req, res) => {
  res.render('settings/admin.html', {
    user: req.session.user
  })
})
// 处理修改密码请求
router.post('/settings/admin', async (req, res) => {
  const body = req.body
  const newPassword = md5(md5(body.checkPassword))
  try {
    await User.updateOne(
      { email: req.session.user.email },
      {
        $set: { "password": newPassword },
        $currentDate: { "lastModified": true }
      })
    res.status(200).json({
      err_code: 0,
      message: 'OK'
    })
  } catch (e) {
    return res.status(500).json({
      err_code: 500,
      message: e.message
    })
  }
})

// 删除用户
router.get('/settings/delete', async (req, res) => {
  try {
    await User.deleteOne({ email: req.session.user.email })
    res.status(200).json({
      err_code: 0,
      message: 'OK'
    })
    req.session.user = null
  } catch (e) {
    return res.status(500).json({
      err_code: 500,
      message: e.message
    })
  }
})

// 处理查询请求
router.get('/select', async (req, res) => {
  try {
    // 输入为空跳转首页
    if (req.query.title == '') {
      res.redirect('/')
    } else {
      // 查询数据 渲染首页页面
      var title = req.query.title
      var re = new RegExp("" + title + "");
      const nice = await Topic.find({ title: { $regex: re } })
      res.render('index.html', {
        user: req.session.user,
        topics: nice
      })
    }


  } catch (e) {
    return res.status(500).json({
      err_code: 500,
      message: e.message
    })
  }

})

module.exports = router
